import Vue from 'vue'
import Router from 'vue-router'

// const _import = (data) => import (data+'.vue')
function getViews(path) {
  return resolve => {
    require.ensure([], (require) => {
      resolve(require('@/view/' + path + '.vue'))
    })
  }
}

//const _import = require('./import-' + process.env.NODE_ENV)
Vue.use(Router)

//静态路由
const StaticRouterMap = [

      { path: '/login', name: 'login', component: getViews('common/login'), meta: { title: '登录' } },
      { path: '/404', name: '404', component:getViews('common/404'), meta: { title: '404' } },
      {
        path: '/',
        name: 'main', 
        component: getViews('main'),
        meta: { title: '主入口整体布局' },
        children:[]
      }
]

const router=new Router({
  mode: 'history',
  routes: StaticRouterMap
})


const dataRoutes = [
    {
      id:1,
      grade:0,
      superior:0,
      icon:'icon-chart-decrease',
      path:'/dataChart',
      title:'图表模块',
      component:'modular/dome/dataChart'
    },
    {
      id:2,
      grade:0,
      superior:0,
      icon:'icon-arrow-four-way',
      path:'/drag',
      title:'拖拽模块',
      component:'modular/dome/drag'
    },
    {
      id:3,
      grade:0,
      superior:0,
      icon:'icon-button-error',
      path:'/error',
      title:'错误模块',
      component:'modular/dome/error'
    },
    {
      id:4,
      grade:0,
      superior:0,
      icon:'icon-pizza',
      path:'/icon',
      title:'图标模块',
      component:'modular/dome/icon'
    },
    {
      id:5,
      grade:0,
      superior:0,
      icon:'icon-bubble-message-dot-2',
      path:'/news',
      title:'消息模块',
      component:'modular/dome/news'
    }
]
var getRouter
router.beforeEach((to, from, next) => {
  const role = JSON.parse(sessionStorage.getItem('user'))
  /**
  *判断是否用户信息为空，当前页面是否是login登录页面
  */
  if(!role){

          if(to.path==="/login"){
              //当前页是登录页面
              sessionStorage.removeItem('user');
              next()
          }else{
              //当前页不是登录页面
              next('/login')
          }

  }else if(!role && to.path !== '/login') {


          //如果当前页面是login登录页面且用户登录信息为空，清除当前登录信息，跳转到登录页面重新登录
          sessionStorage.removeItem('user');
          next('/login');


  }else if(role){
          //路由元信息requireAuth:true，或者homePages:true，则不做登录校验
          if(to.path === '/login'){

                    //当前是登录页面，需要清除用户信息
                    sessionStorage.removeItem('user')
                    sessionStorage.removeItem('menuList')
                    next()

          }else{

                    if (!getRouter) {//不加这个判断，路由会陷入死循环

                                console.log('----进入添加路由----')

                                StaticRouterMap[2].children = ergodicRouter(dataRoutes)
                                router.addRoutes(
                                    StaticRouterMap
                                )
                                sessionStorage.setItem('menuList', JSON.stringify(StaticRouterMap || '[]'))

                                getRouter = StaticRouterMap//后台拿到路由
                                console.log('----添加路由完成----')
                                next({ ...to, replace: true })

                    } else {
                                console.log('----不添加路由----')
                                next()
                    }

          }
  }
})

 //遍历在后台拿过来的路由
 function ergodicRouter(data){

  const dataRouter = []

  for(let i=0;i<data.length;i++){

        if(data[i].grade == 0){

                const dataFa={}
                dataFa['path'] = data[i].path
                dataFa['id'] = data[i].id
                dataFa['icon'] = data[i].icon
                dataFa['name']= data[i].path.replace('/', '')
                dataFa['component'] = getViews(data[i].component)
                const meta ={}
                meta['title'] = data[i].title
                dataFa['meta']= meta
                dataFa['children'] = []
                dataRouter.push(dataFa)
                // dataFa = {}
                // meta = {}

                // for(let y=0;y<data.length;y++){
                //     if(data[i].id == data[y].superior){
                //         const dataCh={}
                //         dataCh.path = data[i].path
                //         dataCh.name= data[i].path
                //         dataCh.component = getViews(data[i].component)
                //         meta.title = data[i].title
                //         dataCh.meta = meta
                //         dataFa.children.push(dataCh)
                //         dataCh = {}
                //         meta = {}
                //     }
                // }

        }
  }
  return dataRouter
}

export default router
